package shuaige.jdk.多线程.concurrent.completableFuture;

import java.util.concurrent.CompletableFuture;

public class 主动完成计算_主动结束立刻获取结果_getNow {
    public static CompletableFuture<Integer> compute(int sleep) {
        final CompletableFuture<Integer> future = new CompletableFuture<>();
        // 异步指向一个任务
        future.completeAsync(() -> {
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 111;
        });
        return future;
    }

    public static void main(String[] args) throws Exception {
        final CompletableFuture<Integer> f1 = compute(1000);
        final CompletableFuture<Integer> f2 = compute(5000);

        new Client("Client1", f1).start();
        new Client("Client2", f2).start();
        System.out.println("waiting");
    }

    /**
     * 新建一个类，用来执行多线程
     */
    static class Client extends Thread {
        // 注入 CompletableFuture
        CompletableFuture<Integer> f;

        Client(String threadName, CompletableFuture<Integer> f) {
            super(threadName);
            this.f = f;
        }

        @Override
        public void run() {
            System.out.println(this.getName() + ": " + f.getNow(122));
        }
    }

}
